Page({
  data: {
    logs: [
      {
        id: 1,
        day: '05',
        month: '06',
        title: '阅读',
        time: '3小时前',
        tag: '坚持阅读，补卡',
        tagColor: '#b3a6d9',
        tagIcon: '../../icon/e-mail.png'
      },
      {
        id: 2,
        day: '19',
        month: '05',
        title: '睡',
        time: '05-19 14:24',
        tag: '坚持阅读，第2天打卡',
        tagColor: '#b3a6d9',
        tagIcon: '../../icon/e-mail.png'
      },
      {
        id: 3,
        day: '18',
        month: '05',
        title: '太开心了',
        time: '05-18 16:59',
        tag: '坚持阅读，第1天打卡',
        tagColor: '#b3a6d9',
        tagIcon: '../../icon/e-mail.png'
      },
      {
        id: 4,
        day: '18',
        month: '05',
        title: '完成',
        time: '05-18 17:08',
        img: '../../images/01.jpg',
        tag: '醒来喝水，第1天打卡',
        tagColor: '#e6b7b7',
        tagIcon: '../../icon/e-mail.png'
      }
    ],
    showEditModal: false,
    editLog: null,
    editContent: '',
    editImages: [],
    searchValue: '',
    filteredLogs: [],
    user_id: '',
    habit_id: '',
    habit_name: ''
  },
  onLoad(options) {
    const user_id = options.user_id;
    const habit_id = options.habit_id;
    const habit_name = decodeURIComponent(options.habit_name || '');
    this.setData({ user_id, habit_id, habit_name });
    console.log('请求日志接口参数', user_id, habit_id);
    this.fetchLogs();
  },
  fetchLogs() {
    const { user_id, habit_id } = this.data;
    console.log('请求日志接口参数', user_id, habit_id);
    wx.request({
      url: 'http://127.0.0.1:3001/getHabitLogs',
      method: 'GET',
      data: { user_id, habit_id },
      success: (res) => {
        console.log('日志数据', res.data);
        if (res.data && Array.isArray(res.data.logs)) {
          // 获取习惯名
          const habit_name = this.data.habit_name || '';
          // 先筛选出所有打卡（log_type==1），用于计数
          const punchLogs = res.data.logs.filter(log => log.log_type == 1);
          const totalDays = punchLogs.length;
          // 最新在前，编号倒序
          let punchIndex = 0;
          const logs = res.data.logs.map(log => {
            let tag = '';
            if (log.log_type == 0) {
              tag = `${habit_name}，补卡`;
            } else {
              // log_type==1，编号为第N天、第N-1天...
              tag = `${habit_name}，第${totalDays - punchIndex}天打卡`;
              punchIndex += 1;
            }
            return {
              ...log,
              day: String(log.log_day).padStart(2, '0'),
              month: String(log.log_month).padStart(2, '0'),
              title: log.log_content,
              time: log.log_CreatedTime ? log.log_CreatedTime.slice(5, 16) : '',
              tag,
              tagColor: '#b3a6d9',
              tagIcon: '../../icon/e-mail.png'
            };
          });
          this.setData({ logs, filteredLogs: logs });
        }
      }
    });
  },
  goBack() {
    wx.navigateBack();
  },
  onSearchInput(e) {
    const value = e.detail.value.trim();
    this.setData({ searchValue: value });
    if (!value) {
      this.setData({ filteredLogs: this.data.logs });
      return;
    }
    const filtered = this.data.logs.filter(item =>
      (item.title && item.title.indexOf(value) !== -1) ||
      (item.tag && item.tag.indexOf(value) !== -1)
    );
    this.setData({ filteredLogs: filtered });
  },
  onMoreTap(e) {
    const logId = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['编辑', '删除'],
      success: (res) => {
        if (res.tapIndex === 0) {
          const log = this.data.logs.find(l => String(l.log_id) === String(logId));
          if (log) {
            this.setData({
              showEditModal: true,
              editLog: log,
              editContent: log.title,
              editImages: log.log_img ? [log.log_img] : []
            });
          } else {
            wx.showToast({
              title: '未找到日志',
              icon: 'none'
            });
          }
        } else if (res.tapIndex === 1) {
          wx.showModal({
            title: '确认删除',
            content: '确定要删除这条日志吗？',
            success: (modalRes) => {
              if (modalRes.confirm) {
                this.deleteLog(logId);
              }
            }
          });
        }
      }
    });
  },
  deleteLog(logId) {
    wx.request({
      url: 'http://127.0.0.1:3001/deleteLogById',
      method: 'POST',
      data: { log_id: logId },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({ title: '已删除', icon: 'none' });
          this.updateHabitNumAfterDelete();
          this.fetchLogs();
        } else {
          wx.showToast({ title: res.data.message || '删除失败', icon: 'none' });
        }
      }
    });
  },
  onEditCancel() {
    this.setData({ showEditModal: false });
  },
  onEditConfirm() {
    const { editLog, editContent, editImages } = this.data;
    wx.request({
      url: 'http://127.0.0.1:3001/updateLog',
      method: 'POST',
      data: {
        log_id: editLog.log_id,
        log_content: editContent,
        log_img: editImages && editImages.length > 0 ? editImages[0] : ''
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({ title: '已修改', icon: 'success' });
          this.setData({ showEditModal: false });
          this.fetchLogs();
        } else {
          wx.showToast({ title: res.data.message || '修改失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  onEditContentInput(e) {
    this.setData({ editContent: e.detail.value });
  },
  onChooseEditImg() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        this.setData({ editImages: res.tempFilePaths });
      }
    });
  },
  onChooseEditVideo() {
    wx.chooseVideo({
      success: (res) => {
        this.setData({ editImages: [res.tempFilePath] });
      }
    });
  },
  onDelEditImg(e) {
    const idx = e.currentTarget.dataset.index;
    const imgs = this.data.editImages.slice();
    imgs.splice(idx, 1);
    this.setData({ editImages: imgs });
  },
  updateHabitNumAfterDelete() {
    const { user_id, habit_id } = this.data;
    wx.request({
      url: 'http://127.0.0.1:3001/getUserHabitDetail',
      method: 'GET',
      data: {
        userId: user_id,
        habitId: habit_id
      },
      success: (res) => {
        if (res.data && typeof res.data.habit_num !== 'undefined') {
          const currentNum = Number(res.data.habit_num) || 0;
          wx.request({
            url: 'http://127.0.0.1:3001/updateHabitNum',
            method: 'POST',
            data: {
              habit_id: habit_id,
              user_id: user_id,
              habit_num: Math.max(currentNum - 1, 0),
              isClockedInToday: 0
            },
            success: () => {
            }
          });
        }
      }
    });
  }
}); 